#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>		 	 
#include <unistd.h>
#include <pthread.h>
#include <errno.h>

#include <linux/input.h>


//服务器
int sockfd;
struct sockaddr_in server;

//客户端
int connfd;
struct sockaddr_in client;

//wifi tcp网络协议初始化
int wifi_tcp_init()
{	
	//1，创建wifi tcp网络协议套接字启动文件：sockfd
	sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	
	int opt = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));
	
	//2，绑定当前wifi服务器ip地址和端口
	bzero(&server,sizeof(server));
	
	server.sin_family = AF_INET;
	server.sin_port = htons(1159);
	server.sin_addr.s_addr = htonl(INADDR_ANY); //可以接受任何地址的数据
	
	//inet_pton(AF_INET,argv[1],&Rose_addr.sin_addr);
	
	bind(sockfd,(struct sockaddr *)&server,sizeof(server));
	
	//3，设置监听，用于限制客户端连接数量
	listen(sockfd,5);
	
	return  sockfd;
}

long long str_to_ll(const char* str) {
    long long result = 0;
    int sign = 1;
    int i = 0;

    if (str[0] == '-') {
        sign = -1;
        i = 1;
    }
    else if (str[0] == '+') {
        i = 1;
    }

    for (; str[i] != '\0'; i++) {
        if (str[i] < '0' || str[i] > '9') {
                return 0;
        }
        result = result * 10 + (str[i] - '0');
    }

    return result * sign;
}

void* read_app_data(void* arg)
{
	pthread_detach(pthread_self());
	int x, y;
    int count = 0;
	
	//4. 等待客户端连接：connfd: 
	socklen_t len= sizeof(client);  //通用结构体变量地址
	
	connfd = accept(sockfd,(struct sockaddr *)&client,&len);
	
	if(connfd > 0) {
		printf("new connect!\n");
	}
	
	//5. 不断接受客户端消息
	char buf[100];
	//char buf[800*640*4];
	//struct buffer currnet_buf;
	FILE* fp=fopen("1.txt","w");
		if (fp == NULL) {
        printf("无法打开文件。\n");
    	exit(-1);
		}

    
	long long msg[3]={0};
	while(1) {
        bzero(buf,100);
		//read(connfd, buf, 800*640*4);
		//read(connfd, currnet_buf.start, currnet_buf.length);
		recv(connfd,buf,sizeof(buf),0);
        long long tmp=str_to_ll(buf);
        printf("%lld \n",tmp);
        fprintf(fp,"%lld %f %f\n",tmp/10000,(float)(tmp%10000/100),(float)(tmp%100));
		// fprintf(fp, "%lld %f %f\n", msg[0],(float)msg[1],(float)msg[2]);
        fflush(fp);
		// printf("Received: %lld %f %f\n", msg[0],(float)msg[1],(float)msg[2]);
		
		
	}
	
    fclose(fp);
	close(connfd);
	
	pthread_exit(NULL);
}

int main(void)
{
	wifi_tcp_init();
	
	pthread_t wifi_tcp_tid;
	
	pthread_create(&wifi_tcp_tid, NULL, read_app_data, NULL);
	
	while(1);
	
	return 0;
}
